#include <unordered_map>

using namespace std;

/**
 * @brief 146. LRU 缓存
 * https://leetcode.cn/problems/lru-cache/
 */
class LRUCache {
public:
    LRUCache(int capacity) : capa(capacity) {
        head = new DLNode;
        tail = new DLNode;
        head->next = tail;
        tail->next = head;
    }

    int get(int key) {
        if (!cache.count(key)) return -1;
        DLNode* node = cache[key];
        remove(node);
        insertFront(node);
        return node->val;
    }

    void put(int key, int value) {
        if (cache.count(key)) {
            cache[key]->val = value;
            DLNode* node = cache[key];
            remove(node);
            insertFront(node);
            return;
        }
        DLNode* node = new DLNode(key, value);
        size += 1;
        if (size > capa) {
            size -= 1;
            deleteLast();
        }
        insertFront(node);
        cache[key] = node;
    }

private:
    struct DLNode {
        int key, val;
        DLNode* prev;
        DLNode* next;
        DLNode() : key(0), val(0), prev(nullptr), next(nullptr) {}
        DLNode(int key, int val) : key(key), val(val), prev(nullptr), next(nullptr) {}
    };

    unordered_map<int, DLNode*> cache;
    DLNode* head = nullptr;
    DLNode* tail = nullptr;
    int capa = 0;
    int size = 0;

    void remove(DLNode* node) {
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }

    void insertFront(DLNode* node) {
        node->next = head->next;
        node->prev = head;
        head->next->prev = node;
        head->next = node;
    }

    void deleteLast() {
        if (tail->prev == head) return;
        DLNode* toDelete = tail->prev;
        remove(toDelete);
        cache.erase(toDelete->key);
        delete toDelete;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
